/***************************************************************************
 *   Copyright (C) 2008 by Milambert									   *
 *   nexus6b@gmail.com   												   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <mysql/mysql.h>
#include "config.h"
#include "common.h"
#include "cardReader.h"
#include "confHandler.h"
#include "mysqlHandler.h"
#include "cardReader.h"

int addCardReader(int local, char *readerAddr){
	MYSQL_RES *result;
	MYSQL_ROW row;
	char query[MAXQUERYLEN];
	int i, idCard;

	//first check if exist
	sprintf(query, "SELECT PK_IDLecteur \
					FROM LecteurCarte \
					WHERE Fk_NumLocal = %d", local);
	
	result = (MYSQL_RES *)mysqlGet(query);
	
	//then add it
	if(((int) mysql_num_rows(result)) == 0 || result == NULL){
		sprintf(query, "INSERT INTO LecteurCarte \
						VALUES(default,'%s',NOW(),'OK',default,%d)",
				readerAddr, local);
		
		mysqlFetch(query);
		
#ifdef DEBUG
		printf("card %d @ %s added\n", local, readerAddr);
#endif
		
	}	
	//or update it
	else{
		while ((row = mysql_fetch_row(result))){
			for(i = 0; i < mysql_num_fields(result); i++){
				idCard =  atoi(row[i]);
			}
		}
			
		updateCardReader(local, idCard, readerAddr, "OK", 0);
	}
	
	//freeResult at last minute
	mysql_free_result(result);
	return 1;
}

int updateCardReader(int local, int idCard, char *readerAddr, char *status, int check){
	char query[MAXQUERYLEN], queryCond[MAXQUERYLEN], tmp[50];
	MYSQL_RES *result;
	MYSQL_ROW row;
	int i;
	
	if(idCard == 0){
		sprintf(query, "SELECT PK_IDLecteur \
						FROM LecteurCarte \
						WHERE Fk_NumLocal = %d", local);
		result = (MYSQL_RES *)mysqlGet(query);

		while ((row = mysql_fetch_row(result))){
			for(i = 0; i < mysql_num_fields(result); i++){
				idCard =  atoi(row[i]);
			}
		}
		mysql_free_result(result);
	}
		
	memset(tmp, 0, sizeof(0));
	sprintf(query, "UPDATE LecteurCarte \
					SET DernierPing = NOW(), Status = '%s' , BadCheck = %d",
			status, check);
	

	if(readerAddr != NULL){
		memset(tmp, 0, sizeof(0));
		sprintf(tmp, ", IPAdresse = '%s'", readerAddr);
		strcat(query, tmp);
	}

	if(local != 0){
		memset(tmp, 0, sizeof(0));
				sprintf(tmp, ", Fk_NumLocal = %d", local);
				strcat(query, tmp);
	}
	
	sprintf(queryCond, " WHERE Pk_IDLecteur = %d", idCard);
	strcat(query, queryCond);
	
	mysqlFetch(query);
	
	return 1;
}

int checkCardReader(void){
	MYSQL_RES *result;
	MYSQL_ROW row;
	char query[MAXQUERYLEN], status[15], str[50];
	int idTmp, numLocTmp, badCheckTmp, i, field = 0;

	//update card reader status (don't need disconnected items)
	sprintf(query, "SELECT Pk_IDLecteur, Fk_NumLocal, Status, BadCheck \
					FROM LecteurCarte \
					WHERE DernierPing < TIMESTAMPADD(SECOND, 20, NOW()) \
					AND NOT STRCMP(Status,'Disconnected') = 0");
	result = (MYSQL_RES *)mysqlGet(query);
	
	while ((row = mysql_fetch_row(result))){
		for(i = 0; i < mysql_num_fields(result); i++){
			switch(field){
				case 0:
					idTmp = atoi(row[i]);
					field++;
					break;
					
				case 1:
					numLocTmp = atoi(row[i]);
					field++;
					break;
					
				case 2:
					strcpy(status, (char *)row[i]);
					field++;
					break;
				
				case 3:
					badCheckTmp = atoi(row[i]);
					field = 0;
					break;
			}
		}
		
#ifdef DEBUG
		printf(" => %d, %d, %s, %d\n", idTmp, numLocTmp, status, badCheckTmp);
#endif

		if(strcmp(status, "OK") == 0){
			updateCardReader(0, idTmp, NULL, "Unknow", badCheckTmp++);
			
			sprintf(str, "W@:	We are losing %d", idTmp);
			writeLog(str);
		}
		
		if(strcmp(status, "Unknow") == 0){

			updateCardReader(0, idTmp, NULL, "Unknow", ++badCheckTmp);
			
			if(badCheckTmp >= 3){
				//update panne table
				memset(query, 0, sizeof(query));
				sprintf(query, "INSERT INTO Panne \
								VALUES(default, NOW(), 'card reader disconnected', 1, %d)",
						numLocTmp);
				
				mysqlFetch(query);
				
				//then uptade cardReader Status
				updateCardReader(0, idTmp, NULL, "Disconnected", badCheckTmp);
				sprintf(str, "E@: 	We have lost %d", idTmp);
				writeLog(str);
			}
		}
		
		/*if(strcmp(status, "Disconnected") == 0){
			//completly Lost => need to remove it
			if(badCheckTmp >= 6)
				removeCardReader(numLocTmp);
			else
				updateCardReader(0, idTmp, NULL, "Disconnected", ++badCheckTmp);
		}*/	
	}
	
	if (!mysql_eof(result)){
		writeLog("EE:	echec eof");
		exit(EXIT_FAILURE);
	}
	
	//freeResult at last minute
	mysql_free_result(result);
	return 1;
}

int removeCardReader(int local){
	char query[MAXQUERYLEN];
	
	sprintf(query, "DELETE FROM LecteurCarte \
					WHERE Fk_NumLocal = %d", local);
	mysqlFetch(query);

#ifdef DEBUG
	char str[25];
	sprintf(str, "I@:	%d removed", local);
	writeLog(str);
#endif
	
	return 1;
}

int requestAuth(int local, char *data){
	MYSQL_RES *result;
	MYSQL_ROW row;
	time_t curTime;
	struct tm *now, begTm;
	char query[MAXQUERYLEN];
	char hourTmp[15];
	int i, resIdTmp, timeTmp, fields = 0, check = 0;
	
	curTime = time(NULL);
	now = localtime(&curTime);
	
	sprintf(query,
			"SELECT Pk_NumRes, DATE_FORMAT(HeureDebut, '%%H:%%i'), Duree \
			FROM Reservation WHERE Fk_Prof = '%s' \
			AND Fk_NumLocal = %d \
			AND (DateRes = DATE_FORMAT(NOW(), '%%Y-%%m-%%d') \
			OR Fk_IDJour = DATE_FORMAT(NOW(), '%%w'))",
			data, local);

	if((result = (MYSQL_RES *)mysqlGet(query)) == NULL){
		//no result => no reservation at all
		mysql_free_result(result);
		return 0;
	}

	if(((int) mysql_num_rows(result)) == 0){
		//no result => reservation at all
		mysql_free_result(result);
		return 0;
	}
	
	//at least 1 result
	while ((row = mysql_fetch_row(result))){
		for(i = 0; i < mysql_num_fields(result); i++){
			switch(fields){
				case 0:
					resIdTmp = atoi(row[i]);
					fields++;
					break;
					
				case 1:
					memset(hourTmp, 0, sizeof(hourTmp));
					strcpy(hourTmp, (char *)row[i]);
					fields++;
					break;
					
				case 2:
					timeTmp = atoi(row[i]);
					fields = 0;
					break;
			}
		}
		
#ifdef DEBUG
		printf(" => %d, %s, %d\n", resIdTmp, hourTmp, timeTmp);
#endif
		
		strptime(hourTmp, "%H:%M", &begTm);
		
		if((begTm.tm_hour <= now->tm_hour) && ((begTm.tm_hour + timeTmp) >= now->tm_hour) && (check == 0)){
			check = 1;
		}
	}
	
	if (!mysql_eof(result)){
		writeLog("EE:	echec eof");
		exit(EXIT_FAILURE);
	}
		
	//freeResult at last minute
	mysql_free_result(result);
	
	if(check == 0)
		return 0;
	
	return 1;
}
